package com.springmq.mq.juc;

import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.threads.TaskThread;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName : TicketTest
 * @Author : lby
 * @Date: 2021/2/3 15:21
 * @Description : juc测试卖票
 */
@Slf4j
public class TicketTest02 {
    public int numbers=10;
    /**
     * 在方法外部new 一个锁
     */
    Lock lock=new ReentrantLock();
    public void sendTicket(){
        // 执行之前加锁
        lock.lock();
        try {
            log.info("抢票人:{},票数:{}",Thread.currentThread().getName(),numbers--);
        }catch (Exception e) {
            e.printStackTrace();
        }
        // 加锁之后必须要解锁
        finally {
            lock.unlock();
        }


    }

    public static void main(String[] args) {
        // 使用lambda表达式调用thread
        TicketTest ticketTest = new TicketTest();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10,10,10, TimeUnit.MINUTES,new SynchronousQueue<Runnable>());
        ThreadPoolExecutor executor02 = new ThreadPoolExecutor(10,10,10, TimeUnit.MINUTES,new SynchronousQueue<Runnable>());
        ThreadPoolExecutor executor03 = new ThreadPoolExecutor(10,10,10, TimeUnit.MINUTES,new SynchronousQueue<Runnable>());
        executor.execute(()->{
            for (int i = 0; i <10 ; i++) {
                ticketTest.sendTicket();
            }
        });
        executor02.execute(()->{
            for (int i = 0; i <10 ; i++) {
                ticketTest.sendTicket();
            }
        });
        executor03.execute(()->{
            for (int i = 0; i <10 ; i++) {
                ticketTest.sendTicket();
            }
        });
    }
}
